/*
 * 介绍:
 */
import { defineStore } from "pinia";
import {
  sdkAutoFindBalance,
  sdkFindApprove,
  sdkApprove,
  sdkFindTxid,
} from "@@/sdk/web3Eth";
import { _require } from "@@/utils/tools";
import {
  apiCoinGameBalance,
  apiCoinList,
  apiWithdrawalInfo,
  ApiWithdrawalInfo,
  ApiCoinList,
} from "@@/api/module/balance";
import { notify } from "@@/hooks/vantHooks";
import { omitText } from "@@/utils/tools/format";
import { copyText } from "@@/utils/tools/project";
import { i18n } from "@@/language";
import { sdkEvaluationSwapTo } from "@@/sdk/web3Eth";

//@ts-ignore
const { t } = i18n.global;

export default defineStore("BalanceStore", {
  //*全局仓库
  state: initState,
  //*全局函数
  actions: {
    async findCoinDefaultPrice(coin: CoinPay | undefined) {
      const USDT = this.getCoinByCode("USDT");
      if (!USDT || !coin) return;
      const currentCoin = this.ethCoinEnum[coin.id];
      if (!currentCoin) return;
      const res = await sdkEvaluationSwapTo(
        1,
        [USDT.contract_addr!, coin.contract_addr!],
        [USDT.format, coin.format],
        this.approveAddresss
      );
      if (!res.status) return;
      currentCoin.defaultPrice = res.data!;
      return res.data!;
    },
    async getWithdrawalInfo(): Promise<ApiWithdrawalInfo.Coin | undefined> {
      const coin = this.getCoinByCode("WKC");
      if (!coin) return;
      const res = await apiWithdrawalInfo();
      if (!res) return;
      this.$patch((state) => {
        const currentCoin = state.ethCoinEnum[coin.id];
        if (!currentCoin) return;
        currentCoin.withdrawal = res.coin;
        currentCoin.gameBalance = res.available.toString();
      });
      return res.coin;
    },
    async getCoinEnum(): Promise<EthCoinEnum | undefined> {
      const res = await apiCoinList();
      if (!res) return;
      const ethCoinEnum: EthCoinEnum = {};
      res.forEach((v) => {
        ethCoinEnum[String(v.id)] = v;
      });
      this.$patch((state) => {
        state.ethCoinEnum = ethCoinEnum;
      });
      return ethCoinEnum;
    },
    async approve(
      coin: CoinPay | undefined,
      amount: number | undefined,
      address: string
    ): Promise<string | undefined> {
      if (!coin?.contract_addr) return;
      let format = coin.format;
      if (!amount) {
        format = 32;
        amount = 99;
      }
      const res = await sdkApprove(coin.contract_addr, amount, format, address);
      if (!res?.status) {
        notify.error(
          res?.message || `${t("pi-zhun")} ${coin.code} ${t("shi-bai")}`
        );
        return res.data;
      }
      const verify = await this.findTxid(res.data!, {
        successMsg: `${t("pi-zhun")} ${coin.code} ${t(
          "jiao-yi-cheng-gong"
        )} ${omitText(res.data)}`,
        failMsg: `${t("pi-zhun")}${coin.code} ${t(
          "jiao-yi-shi-bai"
        )} ${omitText(res.data)}`,
        exceedMsg: t("cha-xun-jiao-yi-zhuang-tai-chao-shi"),
      });
      if (verify) await this.findApprove(coin, address);
      return res.data;
    },
    async findTxid(
      txid: string,
      cfg?: {
        successMsg?: string;
        failMsg?: string;
        exceedMsg?: string;
      }
    ) {
      const defaultCfg = {
        onClick() {
          copyText(txid);
        },
      };
      notify.primary(t("zhen-zai-cha-xun-jiao-yi-zhuang-tai"), {
        duration: -1,
      });
      const verify = await sdkFindTxid(txid);
      if (verify.status === true) {
        notify.success(
          cfg?.successMsg || `${omitText(txid)} ${t("jiao-yi-cheng-gong")}`,
          defaultCfg
        );
        return verify.data;
      } else {
        if (verify.info === 0)
          notify.error(cfg?.exceedMsg || verify.message, defaultCfg);
        notify.error(
          cfg?.failMsg || `${omitText(txid)} ${t("jiao-yi-shi-bai")}`,
          defaultCfg
        );
        return undefined;
      }
    },
    /**检查币种批准状态 */
    checkApprove(
      coin: CoinPay | undefined,
      amount: number,
      address?: string
    ): boolean | undefined {
      if (!coin) return;
      address ??= this.approveAddresss;
      const approveAmount = this.ethCoinEnum[coin.id]?.approve;
      if (!approveAmount || !approveAmount[address]) return;
      return approveAmount[address].amount >= amount;
    },
    /**查询批准金额 */
    async findApprove(
      coin: CoinPay | undefined,
      address?: string
    ): Promise<number | undefined> {
      if (!coin?.contract_addr) return;
      address ??= this.approveAddresss;
      address = address.toLowerCase();
      const res = await sdkFindApprove(
        coin.contract_addr,
        coin.format,
        address
      );
      const currentCoin = this.ethCoinEnum[coin.id];
      const amount = Number(res.data);
      if (!currentCoin || !res.status) return amount;
      currentCoin.approve = { ...currentCoin.approve };
      currentCoin.approve[address] = {
        amount: amount,
      };
      return amount;
    },
    /**查询中心化余额 */
    async findGameBalance(coin: CoinPay | undefined): Promise<void | string> {
      if (!coin) return;
      const res = await apiCoinGameBalance({ coin_id: coin.id });
      const currentCoin = this.ethCoinEnum[coin.id];
      if (!res) return;
      /**查询到的余额 */
      const gameBalcane = res.availbale;
      if (!currentCoin) return gameBalcane;
      return (currentCoin.gameBalance = gameBalcane);
    },
    /**查询dapp钱包余额 */
    async findBalance(coin: CoinPay | undefined): Promise<void | string> {
      if (!coin) return;
      const res = await sdkAutoFindBalance(coin.contract_addr, coin.format);
      const currentCoin = this.ethCoinEnum[coin.id];
      if (!currentCoin || !res?.status) return res?.data;
      return (currentCoin.balance = res.data);
    },
    /**通过code获取币种 */
    getCoinByCode(code: string): StoreCoinItem | undefined {
      if (!this.ethCoinEnum) return;
      for (let key in this.ethCoinEnum) {
        const currentCoin = this.ethCoinEnum[key];
        if (currentCoin?.code.toUpperCase() === code.toUpperCase())
          return currentCoin;
      }
    },
  },
  //*计算属性
  getters: {},
  //*仓库数据缓存
  persist: [
    {
      key: "BalanceStore",
      storage: localStorage, //指定储存位置
    },
  ],
});
/**state类型定义 */
interface BalanceStore {
  ethCoinEnum: EthCoinEnum;
  approveAddresss: string;
}
export interface EthCoinEnum {
  [key: string]: StoreCoinItem;
}
export interface StoreCoinItem extends ApiCoinList.DataItem {
  approve?: AnyObject<Approve>;
  balance?: string;
  gameBalance?: string;
  withdrawal?: Withdrawal;
  defaultPrice?: string;
}
export interface Approve {
  amount: number;
}

export interface Withdrawal extends ApiWithdrawalInfo.Coin {}
/**初始化pinia */
function initState(): BalanceStore {
  return {
    ethCoinEnum: {},
    approveAddresss: "",
  };
}
